package com.micookie.v2ex.utils;

import android.util.Log;

import com.micookie.v2ex.model.bean.Member;
import com.micookie.v2ex.model.bean.Node;
import com.micookie.v2ex.model.bean.Reply;
import com.micookie.v2ex.model.bean.Topic;
import com.micookie.v2ex.model.bean.TopicDetail;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/1.
 */

public class ParseUtils {
    private static final String TAG = "ParseUtils";

    /**
     * 解析主题列表
     *
     * @param html
     * @return
     */
    public static List<Topic> parseTopicList(String html) {
        Document document = Jsoup.parse(html);
        Elements topicNodeElements = document.body().select("#TopicsNode");
        Elements topicElements;
        Node nodeInfo = null;
        int pageCount;

        boolean isNode = !topicNodeElements.isEmpty();//通过#TopicsNode, 判断是节点列表,还是tab列表

        if (isNode) {
            topicElements = topicNodeElements.select(".cell");
            nodeInfo = parseNodeInfo(document);
            pageCount = checkPagesCount(document);
        } else {
            topicElements = document.body().select(".cell.item");
        }

        List<Topic> topicList = new ArrayList<>();
        for (Element topicElement : topicElements) {
            topicList.add(parseTopic(topicElement, isNode, nodeInfo));
        }
        return topicList;
    }

    /**
     * 解析单个主题
     * 标题、节点、创建时间等
     *
     * @param topicElement
     * @param isNode       是否是节点列表页面
     * @param nodeInfo     当前节点信息(如果是节点列表页面,需要使用传递提供的节点信息,当前不能解析出来）
     * @return
     */

    private static Topic parseTopic(Element topicElement, boolean isNode, Node nodeInfo) {
        Topic topic = new Topic();
        Node node = new Node();
        Member member = new Member();

        Elements tds = topicElement.select("td");
        String avatarUrl = tds.eq(0).select("img").attr("src");
        String title = tds.eq(2).select(".item_title").select("a").text();
        String url = tds.eq(2).select(".item_title").select("a").attr("href");

        Elements infoTemp = tds.eq(2).select(".small.fade");

        String nodeName = infoTemp.select(".node").html();
        String nodeUrl = infoTemp.select(".node").select("a").attr("href");

        String userName = infoTemp.select("a").eq(1).text();

        String repliesString = tds.eq(3).text().trim();
        int replies = Integer.parseInt(repliesString.equals("") ? "0" : repliesString);

        String replyInfo = infoTemp.text().replaceAll("[\\s\\u00A0]", "");//去掉ASCII 为32和160的空格
        String lastReply = "";
        String createdFormat = "";
        if (replyInfo.contains("前•最后回复来自")) {
            lastReply = infoTemp.select("strong").eq(1).text(); //最后回复来自xxx
            String[] replyArray = replyInfo.split("•");
            if (replyArray.length == 4) {
                createdFormat = replyArray[2]; //5天前
            } else if (replyArray.length == 3) { //如果是节点列表情况下，只能取到3个
                createdFormat = replyArray[1]; //5天前
            }
        }


        topic.setTitle(title);
        topic.setUrl(url);
        topic.setReplies(replies);
        topic.setCreatedFormat(createdFormat);
        topic.setLastReply(lastReply);
        member.setUserName(userName);
        member.setAvatar(avatarUrl);
        node.setName(nodeName);
        node.setUrl(nodeUrl);
        topic.setMember(member);
        //如果当前是节点列表页面，使用传递过来的节点信息（因为当前方法无法解析出）
        topic.setNode((isNode && nodeInfo != null) ? nodeInfo : node);
        return topic;
    }


    public static TopicDetail parseTopicDetail(String topicDetailHtml) {
        TopicDetail topicDetail = new TopicDetail();
        List<Reply> replyList = new ArrayList<>();
        //解析主题信息
        Document document = Jsoup.parse(topicDetailHtml);
        //检查回复页数
        topicDetail.setPageCount(checkPagesCount(document));

        topicDetail.setTopic(parseTopicDetailHeader(document));
        //解析回复信息
        Elements replyElements = document.select("div[id^=r_]");
        for (Element replyElement : replyElements) {
            replyList.add(parseReply(replyElement));
        }
        topicDetail.getReplyList().addAll(replyList);

        return topicDetail;
    }

    /**
     * 解析主题详情页面的主题信息
     *
     * @return
     */
    private static Topic parseTopicDetailHeader(Document pageDocument) {
        Topic topic = new Topic();

        String url = pageDocument.select("link[rel=canonical]").attr("href");
        String title = pageDocument.select(".header").select("h1").text();
        String content = pageDocument.select(".topic_content").toString();
        String avatar = pageDocument.select(".header").select(".fr").select("img").attr("src");
        String otherInfo = pageDocument.select(".header").select("small.gray").text();

        String userName = "";
        String createdFormat = "";
        int click = 0;
        String[] otherInfoArray = otherInfo.split("·");
        if (otherInfoArray.length == 3) {
            userName = otherInfoArray[0];
            createdFormat = otherInfoArray[1]; //5天前
            click = Integer.parseInt(StringUtils.RemoveNotNum(otherInfoArray[2]));//剔除所有非数字
        }


        topic.setCreatedFormat(createdFormat);
        topic.setClicks(click);
        topic.getMember().setUserName(userName);
        topic.getMember().setAvatar(avatar);

        topic.setUrl(url);
        topic.setTitle(title);
        topic.setContent(content);
        return topic;
    }


    /**
     * 解析单个回复信息
     *
     * @param replyElement
     * @return
     */
    private static Reply parseReply(Element replyElement) {

        Reply reply = new Reply();

        String replyContent = replyElement.select(".reply_content").html();
        String avatar = replyElement.select("td").eq(0).select("img").attr("src");
        String userName = replyElement.select("td").eq(2).select(".dark").text();
        String createdFormat = replyElement.select("td").eq(2).select(".fade.small").text();
        String floorNum = replyElement.select("td").eq(2).select("span.no").text();

        reply.setContent(replyContent);
        reply.setCreatedFormat(createdFormat);
        reply.setFloorNum(floorNum);
        reply.getMember().setUserName(userName);
        reply.getMember().setAvatar(avatar);

        return reply;
    }


    /**
     * 根据整个页面解析当前节点信息(用于节点列表的情况)
     *
     * @param wholePageDocument
     * @return
     */
    private static Node parseNodeInfo(Document wholePageDocument) {
        String title = wholePageDocument.select("title").text();
        title = title.replaceAll("[\\s\\u00A0]", "").replace("V2EX›", "");//去空，去掉无用信息
        return new Node().setName(title);
    }

    /**
     * 检查页数,适用于评论和列表页
     *
     * @return
     */
    private static int checkPagesCount(Element topicDetailElement) {
        Elements elements = topicDetailElement.select("a[class^=page_]");
        String pageNum = "1";
        if (!elements.isEmpty()) {
            pageNum = elements.last().text();
        }
        Log.d(TAG, "checkPagesCount();检查总页数---pageNum：" + pageNum);
        return pageNum.matches("\\d+") ? Integer.parseInt(pageNum) : 1;
    }
}
